<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/3/26
 * Time: 22:08
 */

namespace app\common\logic;


use app\common\model\mysql\Category;

class CategoryLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new Category();
    }

    /**
     * 获取所有分类
     * @return array
     */
    public function getCategoryLists()
    {
        $where  = [
            "status" => 1,
            "order"  => "order desc",
        ];
        $result = $this->model->getLists($where);

        return $result->toArray();
    }

    /**
     * @param $data
     * @return bool
     * @throws \think\Exception
     */
    public function addCategory($data)
    {
        $result = $this->model->addData($data);
        if (!$result) {
            throw new \think\Exception("添加失败");
        }

        return true;
    }

    /**
     * @param $id
     * @return array|mixed
     */
    public function getCategoryOneById($id)
    {
        $result = $this->model->getOneDataById($id);
        if (empty($result)) {
            return [];
        }

        return $result;
    }

    /**
     * 编辑分类
     * @param $id
     * @param $data
     * @return bool
     * @throws \think\Exception
     */
    public function updateCategory($id, $data)
    {
        $result = $this->model->updateDataById($id, $data);
        if (false === $result) {
            throw new \think\Exception("分类编辑失败");
        }

        return true;
    }

    /**
     * 删除分类
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function deleteById($id)
    {
        $subCategory = $this->model->where('pid', $id)->count();
        if ($subCategory > 0) {
            throw new \think\Exception("该分类下有子分类，请先删除子分类，再进行删除!");
        }
        $result = $this->model->deleteOneData($id);
        if (!$result) {
            throw new \think\Exception("分类删除失败");
        }

        return $result;
    }
}